package com.googlecode.jtoy.patterns.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.googlecode.jtoy.patterns.proxy.Advice;

/**
 * Jdk动态代理
 * 
 * @author shangxj
 * @date Jun 18, 2011 11:46:28 PM
 */
public class JdkProxyFactory implements InvocationHandler {

	private Advice advice;

	private Object target;

	public JdkProxyFactory(Advice advice) {

		this.advice = advice;
	}

	public Object newProxyInstance(Object target) {

		this.target = target;
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass()
				.getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

		Object returnValue = null;

		if (advice.around(args[0])) {

			advice.before();

			try {
				returnValue = method.invoke(target, args);

				advice.afterReturn();
			}
			catch (RuntimeException e) {
//				e.printStackTrace();
				advice.afterException();
			}
			finally {
				advice.after();
			}
		}

		return returnValue;
	}
}
